import React, { useEffect } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { Form, Input, Button, Checkbox, Alert, Typography, Row, Col } from 'antd';
import { UserOutlined, LockOutlined, RocketOutlined } from '@ant-design/icons';
import { useAuthStore } from '../store/auth';

const { Title, Text } = Typography;

const LoginPage: React.FC = () => {
  const [form] = Form.useForm();
  const { login, isLoading, error, clearError, isAuthenticated } = useAuthStore();
  const navigate = useNavigate();
  const location = useLocation();

  // 如果已经登录，重定向到仪表板
  useEffect(() => {
    if (isAuthenticated) {
      const from = (location.state as any)?.from?.pathname || '/app/dashboard';
      navigate(from, { replace: true });
    }
  }, [isAuthenticated, navigate, location]);

  // 清除错误信息当组件卸载时
  useEffect(() => {
    return () => {
      clearError();
    };
  }, [clearError]);

  const handleSubmit = async (values: any) => {
    clearError();
    try {
      await login({
        username: values.username.trim(),
        password: values.password,
      });
      
      // 登录成功后导航到目标页面
      const from = (location.state as any)?.from?.pathname || '/app/dashboard';
      navigate(from, { replace: true });
    } catch (error) {
      // 错误处理由store管理
    }
  };

  return (
    <>
      <div style={{ minHeight: '100vh', display: 'flex' }}>
        <Row style={{ width: '100%', minHeight: '100vh' }}>
          {/* 左侧紫色渐变背景 */}
          <Col xs={0} md={12} lg={14} xl={16} style={{
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            position: 'relative',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            overflow: 'hidden'
          }}>
            {/* 装饰性几何图形 */}
            <div style={{ position: 'absolute', width: '100%', height: '100%' }}>
              {[...Array(6)].map((_, i) => (
                <div
                  key={i}
                  style={{
                    position: 'absolute',
                    width: `${120 + i * 40}px`,
                    height: `${120 + i * 40}px`,
                    backgroundColor: 'rgba(255, 255, 255, 0.1)',
                    borderRadius: '12px',
                    transform: `rotate(${i * 15}deg)`,
                    top: `${20 + i * 10}%`,
                    left: `${15 + i * 8}%`,
                    animation: `float ${3 + i * 0.5}s ease-in-out infinite alternate`
                  }}
                />
              ))}
            </div>

            {/* 主要内容 */}
            <div style={{ 
              position: 'relative', 
              zIndex: 2, 
              textAlign: 'center',
              color: 'white',
              maxWidth: '400px',
              padding: '0 40px'
            }}>
              <div style={{ marginBottom: '32px' }}>
                <RocketOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                <Title level={2} style={{ color: 'white', fontSize: '28px', marginBottom: '8px' }}>
                  星链saas运维系统
                </Title>
              </div>
              
              <Title level={1} style={{ 
                color: 'white', 
                fontSize: '48px', 
                fontWeight: 'bold',
                marginBottom: '24px',
                lineHeight: 1.2
              }}>
                欢迎回来
              </Title>
              
              <Text style={{ 
                color: 'rgba(255, 255, 255, 0.8)', 
                fontSize: '18px',
                lineHeight: 1.6
              }}>
                登录您的账户，继续您的运维管理之旅
              </Text>

              {/* 装饰性小圆点 */}
              {[...Array(3)].map((_, i) => (
                <div
                  key={i}
                  style={{
                    position: 'absolute',
                    width: '8px',
                    height: '8px',
                    backgroundColor: 'rgba(255, 255, 255, 0.4)',
                    borderRadius: '50%',
                    top: `${60 + i * 15}%`,
                    right: `${10 + i * 5}%`,
                    animation: `pulse ${2 + i * 0.3}s ease-in-out infinite`
                  }}
                />
              ))}
            </div>
          </Col>

          {/* 右侧登录表单 */}
          <Col xs={24} md={12} lg={10} xl={8} style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '40px',
            backgroundColor: '#fff'
          }}>
            <div style={{ width: '100%', maxWidth: '400px' }}>
              {/* 表单头部 */}
              <div style={{ textAlign: 'right', marginBottom: '40px' }}>
                <Title level={2} style={{ marginBottom: '8px', color: '#262626' }}>
                  账户登录
                </Title>
                <Text type="secondary" style={{ fontSize: '14px' }}>
                  <Link to="/register" style={{ color: '#1890ff', textDecoration: 'none' }}>
                    创建新账户 →
                  </Link>
                </Text>
              </div>

              {error && (
                <Alert
                  message={error}
                  type="error"
                  showIcon
                  closable
                  onClose={clearError}
                  style={{ marginBottom: '24px' }}
                />
              )}

              <Form
                form={form}
                name="login"
                onFinish={handleSubmit}
                autoComplete="off"
                size="large"
              >
                <Form.Item
                  name="username"
                  rules={[
                    { required: true, message: '请输入用户名或邮箱!' },
                    { min: 3, message: '用户名或邮箱至少3个字符' }
                  ]}
                >
                  <Input
                    prefix={<UserOutlined style={{ color: '#999' }} />}
                    placeholder="请输入用户名或邮箱"
                    disabled={isLoading}
                    style={{ 
                      borderRadius: '8px',
                      border: '1px solid #e8e8e8',
                      padding: '12px 16px'
                    }}
                  />
                </Form.Item>

                <Form.Item
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码!' },
                    { min: 6, message: '密码至少6个字符' }
                  ]}
                >
                  <Input.Password
                    prefix={<LockOutlined style={{ color: '#999' }} />}
                    placeholder="请输入密码"
                    disabled={isLoading}
                    style={{ 
                      borderRadius: '8px',
                      border: '1px solid #e8e8e8',
                      padding: '12px 16px'
                    }}
                  />
                </Form.Item>

                <Form.Item style={{ marginBottom: '24px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Form.Item name="remember" valuePropName="checked" noStyle>
                      <Checkbox>记住我</Checkbox>
                    </Form.Item>
                    <Link to="#" style={{ color: '#1890ff', fontSize: '14px' }}>
                      忘记密码？
                    </Link>
                  </div>
                </Form.Item>

                <Form.Item style={{ marginBottom: '16px' }}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={isLoading}
                    style={{ 
                      width: '100%',
                      height: '48px',
                      borderRadius: '8px',
                      fontSize: '16px',
                      fontWeight: 500,
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      border: 'none',
                      boxShadow: '0 4px 12px rgba(102, 126, 234, 0.4)'
                    }}
                  >
                    登录
                  </Button>
                </Form.Item>

                <div style={{ textAlign: 'center' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    还没有账号？
                    <Link to="/register" style={{ color: '#1890ff', marginLeft: '4px' }}>
                      立即注册
                    </Link>
                  </Text>
                </div>
              </Form>


            </div>
          </Col>
        </Row>
      </div>

      {/* CSS动画 */}
      <style>
        {`
          @keyframes float {
            0% { transform: translateY(0px) rotate(0deg); }
            100% { transform: translateY(-10px) rotate(5deg); }
          }
          
          @keyframes pulse {
            0%, 100% { opacity: 0.4; transform: scale(1); }
            50% { opacity: 0.8; transform: scale(1.2); }
          }
        `}
      </style>
    </>
  );
};

export default LoginPage; 